import React, {Component} from 'react';
import {Button, Dimensions, ScrollView, StyleSheet, Text, TouchableOpacity, View} from 'react-native';
import {SafeAreaView} from 'react-native-safe-area-context';
import {HeaderTitle} from '../../../../../../componet/settingComponent/HeaderTitle';
import {BrLine} from '../../../../../../componet/settingComponent/BrLine';
import {CardItem} from '../../../../../../componet/settingComponent/CardItem';
import AllStyle from '../../../../../../style';
import {Toast} from '../../../../../../utils/Toast';
import {Loading} from '../../../../../../utils/Loading';
import Icons from 'react-native-vector-icons/Entypo';
import AntDesign from 'react-native-vector-icons/AntDesign';
import {getUserList} from '../../../../../../api/user';
import {getUserIdListByNotInGroup} from '../../../../../../api/empPlanClasses';
import {BottomButton} from '../../../../../../componet/settingComponent/BottomButton';


const width = Dimensions.get('window').width;


export class SignEmp extends Component {


    constructor(props) {
        super(props);
        this.state = {
            empPlanClassesId: this.props.route.params.empPlanClassesId!=null?this.props.route.params.empPlanClassesId:null,
            routePathName: this.props.route.params.routePathName,
            visible: this.props.route.params.visible == null ? true : false,
            selectedIndex: this.props.route.params.userIds,
            name: '',
            userList: [],
        };
    }

    componentDidUpdate(prevProps: Readonly<P>, prevState: Readonly<S>, snapshot: SS) {

        // if (this.props.route.params != prevProps.route.params) {
        //     this.getList();
        // }

    }

    componentDidMount() {
        this.getList();
    }

    changeSelectedIndex = (id) => {
        let userList = this.state.userList;
        userList = userList.map((item, index) => {
            if (item.userId == id) {
                item.selectedIndex = item.selectedIndex == 1 ? 0 : 1;
            }
            return {
                ...item,
            };
        });
        this.setState({userList});
    };

    back = () => {

        const route = {
            name: this.state.routePathName,
            params: {},
        };
        this.props.navigation.navigate(route);
    };
    goto = (name, params) => {

        const route = {
            name: name,
            params:{
                ...params
            }

        };
        this.props.navigation.navigate(route);
    };
    check = () => {
        let userList = this.state.userList;
        let userIds=[];
        for(let i of userList){
            if(i.selectedIndex==1){
                userIds.push(i.userId)
            }
        }
        if (userIds.length <= 0) {
            Toast.showWarning('请选择考勤人员');
            return;
        }
        let data = {
            empPlanClassesId: this.state.empPlanClassesId,
            userIds: userIds,
        };
        Loading.show()
        getUserIdListByNotInGroup(data).then(res => {
            Loading.hidden()
            console.log(res,'res')
            let {data}=res
            if (data){
                //xxx用户添加不成功，因为他们在其他考勤组中
                let msg='';
                for (let i of data){
                    for (let j of userList){
                        if (i==j.userId){
                            msg+=j.username.toString()+' ';
                        }
                    }
                }
                msg+='已经在其他考勤组中不允许添加'
                Toast.showWarning(msg)
            }else {
                //添加到考勤组操作
                this.goto('SaveSignPlanGroup',{title:"保存考勤方案组",userIds:userIds})
            }


        }).catch(err => {
            Loading.hidden()
            Toast.showWarning(err.toString())
        }).finally(()=>{
            Loading.hidden();
        });
    };
    getList = () => {
        let data = {
            page: 1,
            limit: 100,
        };
        Loading.show();
        getUserList(data).then(res => {
                Loading.hidden();
                let {page} = res;
                let userList = page.list;
                userList = userList.map((item, i) => {
                    let sl = this.state.selectedIndex;
                    let selectedIndex;

                    for (let value of sl) {
                        if (value == item.userId) {
                            selectedIndex = 1;
                            return {
                                username: item.username, userId: item.userId, selectedIndex: selectedIndex,
                            };
                        } else {
                            selectedIndex = 0;

                        }

                    }
                    return {
                        username: item.username, userId: item.userId, selectedIndex: selectedIndex,
                    };
                });
                this.setState({userList: userList});
            },
        ).catch(err => {
            Loading.hidden();
            Toast.showWarning(err.toString());
        }).finally(()=>{
            Loading.hidden();
        });
    };

    render() {
        let itemWidth;
        if (this.state.visible == true) {
            itemWidth = width - 15 - 15 - 15 - 15 - 18 - 15;
        } else {
            itemWidth = width - 15 - 15 - 15 - 15;
        }
        //console.log(this.props.route);
        return (
            <SafeAreaView edges={['top', 'left', 'right', 'bottom']} style={{flex: 1, backgroundColor: '#ffffff'}}>
                <View style={style.container}>
                    <HeaderTitle goBack={() => this.back()} headtitle={this.props.route.params.title}></HeaderTitle>
                    <ScrollView style={{padding: 15}}>
                        <View style={[AllStyle.card]}>
                            {
                                this.state.userList.map((item, i) => {
                                    return (
                                        <View key={i} style={{
                                            flexDirection: 'row',
                                            justifyContent: 'space-between',
                                            alignItems: 'center',
                                        }}>
                                            {this.state.visible == true ? (
                                                <TouchableOpacity style={{paddingRight: 15}} onPress={() => {
                                                    this.changeSelectedIndex(item.userId);
                                                }}>
                                                    {
                                                        item.selectedIndex == 1 ?
                                                            (<AntDesign name={'checkcircle'} style={{color: '#409EFF'}}
                                                                        size={18}/>) :
                                                            (<Icons name={'circle'} style={{color: '#9FA5AB'}}
                                                                    size={18}/>)
                                                    }
                                                </TouchableOpacity>
                                            ) : (
                                                <View></View>
                                            )}

                                            <TouchableOpacity style={{width: itemWidth}} key={item.userId}
                                                              onPress={() => this.changeSelectedIndex(item.userId)}>

                                                <CardItem title={item.username}
                                                          value={item.selectedIndex == 1 ? '已选' : '未选'}></CardItem>

                                                <BrLine></BrLine>
                                            </TouchableOpacity>
                                        </View>

                                    );
                                })
                            }
                        </View>
                    </ScrollView>
                    <BottomButton click={() => {
                        this.check();
                    }} title={'确认选择'}></BottomButton>
                </View>
            </SafeAreaView>
        );
    }

}

const style = StyleSheet.create({
    container: {
        backgroundColor: '#F1F0F5',
        flex: 1,
    },
    con_top: {
        backgroundColor: '#fff',
        borderBottomWidth: 1,
        borderStyle: 'solid',
        borderColor: '#E8E8EA',
        width: width,
        padding: '3%',
        flexDirection: 'row',
    },

});
